package easier.data.store;

import android.content.Context;
import androidx.datastore.core.Serializer;
import androidx.datastore.rxjava3.RxDataStore;
import androidx.datastore.rxjava3.RxDataStoreBuilder;
import com.google.protobuf.MessageLite;
import io.reactivex.rxjava3.core.Flowable;
import io.reactivex.rxjava3.core.Single;
import io.reactivex.rxjava3.functions.Function;

/**
 * 使用protobuf保存数据
 * <p>
 * 1.plugins {
 * id 'com.android.application'
 * id "com.google.protobuf" version "0.8.17"
 * }
 * <p>
 * 2.protobuf {
 * protoc {
 * artifact = "com.google.protobuf:protoc:3.14.0"
 * }
 * <p>
 * // Generates the java Protobuf-lite code for the Protobufs in this project. See
 * // https://github.com/google/protobuf-gradle-plugin#customizing-protobuf-compilation
 * // for more information.
 * generateProtoTasks {
 * all().each { task ->
 * task.builtins {
 * java {
 * option 'lite'
 * }
 * }
 * }
 * }
 * }配置在android{}同级
 * <p>
 * 3.创建proto文件,build生成
 * <p>
 * https://developer.android.com/codelabs/android-proto-datastore?hl=zh_cn#0
 *
 * @param <T>
 */
public class RxProtoStoreManager< T extends MessageLite > {

    private final RxDataStore< T > dataStore;
    private final Flowable< T > mData;

    public RxProtoStoreManager( Context context, String name, Serializer< T > serializer ) {

        dataStore = new RxDataStoreBuilder< T >( context, /* fileName= */ name, serializer ).build();
        mData = dataStore.data();
    }

    public Flowable< T > observeProto() {

        return mData;
    }

    public void updateData( Function< T, Single< T > > function ) {

        dataStore.updateDataAsync( function );
    }

    public void dispose() {

        dataStore.dispose();
        dataStore.shutdownComplete().blockingAwait();
    }
}
